package com.citic.topview.system.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.citic.topview.common.annotation.Log;
import com.citic.topview.common.util.IdGen;
import com.citic.topview.common.util.Servlets;
import com.citic.topview.system.service.LogService;
import com.citic.topview.system.util.IPUtils;
import com.citic.topview.system.util.JSONUtils;
import com.citic.topview.system.util.ShiroUtils;

@Aspect
@Component
@Order(2)
public class LogAspect {

	public static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
	
	//private Gson gson = new GsonBuilder().create();
	
	@Autowired
	private LogService logService;
	
	@Pointcut("@annotation(com.citic.topview.common.annotation.Log)")
	public void logPointCut() {
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		Object result = point.proceed();
		long time = System.currentTimeMillis() - beginTime;
		saveLog(point, time);
		return result;
	}

	private void saveLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		com.citic.topview.common.system.entity.Log log = new com.citic.topview.common.system.entity.Log();
		Log l = method.getAnnotation(Log.class);
		if (l != null) {
			// 注解上的描述
			log.setOperation(l.value());
		}
		
		HttpServletRequest request = Servlets.getRequest();
		
		// 请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		log.setMethod(className + "." + methodName + "()");
		try {
			String params = JSONUtils.beanToJson(request.getParameterMap());
			log.setParams(params);
		} catch (Exception e) {

		}
		
		// 获取request 设置IP地址
		log.setIp(IPUtils.getIpAddr(request));
		log.setUrl(request.getServletPath());
		log.setUsername(ShiroUtils.getPrincipal().getName());
		log.setUserId(ShiroUtils.getPrincipal().getId());
		log.setTime(time);
		log.setId(IdGen.snowFlakeId());
		
		// 系统当前时间
		Date date = new Date();
		log.setCreateTime(date);
		log.setModifiedTime(date);
		log.setDelFlag("0");
		
		logService.save(log);
	}
}
